package com.yiwei.jmx.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.bumptech.glide.Glide;
import com.yiwei.jmx.R;
import com.yiwei.jmx.api.Api;
import com.yiwei.jmx.api.bean.BankcardPresignBean;
import com.yiwei.jmx.api.bean.DealApplyBean;
import com.yiwei.jmx.api.bean.DealIndexDetailBean;
import com.yiwei.jmx.api.bean.DealInfoBean;
import com.yiwei.jmx.api.model.BankCardListModel;
import com.yiwei.jmx.api.model.DealIndexDetailModel;
import com.yiwei.jmx.api.model.DealInfoModel;
import com.yiwei.jmx.base.BaseActivity;
import com.yiwei.jmx.constant.UserInfoGlobal;
import com.yiwei.jmx.event.BorrowUseEvent;
import com.yiwei.jmx.event.ChangeHomePageEvent;
import com.yiwei.jmx.util.Dialog;
import com.yiwei.jmx.util.Network;
import com.yiwei.jmx.util.RxLifeUtil;
import com.yiwei.jmx.util.Spans;
import com.yiwei.jmx.util.ToastUtil;
import com.yiwei.jmx.util.UI;
import com.yiwei.jmx.util.Util;
import com.yiwei.jmx.view.BankSelectDialog;
import com.yiwei.jmx.view.BorrowMoneyTipsDilaog;
import com.yiwei.jmx.view.CircularProgress;
import com.yiwei.jmx.view.PhoneIdentityDilaog;
import com.yiwei.jmx.view.SelectMenuDilaog;
import com.yiwei.jmx.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class BorrowStepActivity extends BaseActivity implements Handler.Callback {

    @BindView(R.id.txt_title)
    TextView txtTitle;

    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.btn_wechat)
    ImageView btnWechat;
    @BindView(R.id.btn_tips)
    ImageView btnTips;
    @BindView(R.id.edit_money)
    EditText editMoney;
    @BindView(R.id.btn_all)
    TextView btnAll;
    @BindView(R.id.txt_borrow_tips)
    TextView txtBorrowTips;
    @BindView(R.id.btn_menu_one)
    RelativeLayout btnMenuOne;
    @BindView(R.id.btn_menu_two)
    RelativeLayout btnMenuTwo;
    @BindView(R.id.btn_menu_three)
    RelativeLayout btnMenuThree;
    @BindView(R.id.btn_menu_four)
    RelativeLayout btnMenuFour;
    @BindView(R.id.txt_get_money)
    TextView txtGetMoney;
    @BindView(R.id.txt_repay_money)
    TextView txtRepayMoney;
    @BindView(R.id.txt_repay_tips)
    TextView txtRepayTips;
    @BindView(R.id.txt_time)
    TextView txtTime;
    @BindView(R.id.img_bank_icon)
    ImageView imgBankIcon;
    @BindView(R.id.txt_bank_account)
    TextView txtBankAccount;
    @BindView(R.id.layout_bank)
    FrameLayout layoutBank;
    @BindView(R.id.txt_service_fee)
    TextView txtServiceFee;
    @BindView(R.id.btn_check)
    ImageView btnCheck;
    @BindView(R.id.btn_submit)
    SuperButton btnSubmit;
    @BindView(R.id.txt_agree)
    TextView txtAgree;
    @BindView(R.id.txt_tips)
    TextView txtTips;
    @BindView(R.id.txt_menu_one)
    TextView txtMenuOne;
    @BindView(R.id.txt_menu_two)
    TextView txtMenuTwo;
    @BindView(R.id.txt_menu_three)
    TextView txtMenuThree;
    @BindView(R.id.txt_menu_four)
    TextView txtMenuFour;
    @BindView(R.id.txt_borrow_place)
    TextView txtBorrowPlace;
    @BindView(R.id.loading_sec)
    CircularProgress loadingSec;
    @BindView(R.id.btn_check_one)
    ImageView btnCheckOne;
    @BindView(R.id.txt_agree_one)
    TextView txtAgreeOne;

    private Unbinder unbiner;
    private PhoneIdentityDilaog phoneIdentityDilaog;
    private BankSelectDialog bankSelectDialog;
    private DealIndexDetailModel.DataBean totalData;
    private SelectMenuDilaog selectMenuDilaog;
    private DealApplyBean submitBean;
    private boolean isNeedBankSign = true;
    MyHandler mHandler = new MyHandler(this);
    private DealInfoBean calculatorBean = new DealInfoBean();
    private float auth_money;
    private int x22;
    private boolean isAgree = false;
    private boolean isAgreeOne = false;
    private BorrowMoneyTipsDilaog borrowMoneyTipsDilaog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_borrow_step);
        initBar();
        setBarClick();
        unbiner = ButterKnife.bind(this);
        init();
        EventBus.getDefault().register(this);
    }

    private void init() {
        borrowMoneyTipsDilaog = new BorrowMoneyTipsDilaog(this);
        submitBean = new DealApplyBean();
        totalData = getIntent().getParcelableExtra("data");
        String company_id = getIntent().getStringExtra("company_id");
        String channel_id = getIntent().getStringExtra("channel_id");
        if (totalData != null) {
            initData();
        } else {
            getDealIndexDetail(company_id, channel_id);
        }


        selectMenuDilaog = new SelectMenuDilaog(this);
        selectMenuDilaog.setOnChooseListener(new SelectMenuDilaog.OnChooseListener() {
            @Override
            public void onSuccess(int poi, String text, String menuType) {
                if (menuType.equals("time")) {
                    txtMenuOne.setText(text + "天");
                    submitBean.day = text;
                    calculatorBean.day = text;
                    if (!TextUtils.isEmpty(calculatorBean.money)) {
                        getDealInfo();
                    }
                }
            }
        });

        x22 = getResources().getDimensionPixelSize(R.dimen.x22);

        txtTips.setText(getServiceTips("0", "0.00"));
        Spanned txt_agree = Spans.with(this).font("点击下一步即表示您同意", x22, 0xff566F8E).font("《借款协议》", x22, 0xff0072FF).build();
        txtAgree.setText(txt_agree);

        Spanned txt_agree_one = Spans.with(this).font("我已阅读并同意信贷机构的", x22, 0xff566F8E).font("《代收委托书》", x22, 0xff0072FF).build();
        txtAgreeOne.setText(txt_agree_one);

        phoneIdentityDilaog = new PhoneIdentityDilaog(this);
        phoneIdentityDilaog.setOnChooseListener(new PhoneIdentityDilaog.OnChooseListener() {
            @Override
            public void onSuccess() {
                Util.startActivity(BorrowStepActivity.this, LoanAgreementActivity.class);
                finish();
            }
        });
        bankSelectDialog = new BankSelectDialog(this);
        bankSelectDialog.setOnSelect(new BankSelectDialog.OnSureListener() {
            @Override
            public void onSure(BankCardListModel.DataBean item) {
                submitBean.bankcard_id = item.id;
                Glide.with(BorrowStepActivity.this).load(item.icon).into(imgBankIcon);
                txtBankAccount.setText("(" + item.bank_name + item.last_num + ")");
            }
        });

        editMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (UI.toString(editMoney).length() == 0) {
                    txtGetMoney.setText("￥0.00");
                    txtRepayMoney.setText("￥0.00");

                    txtServiceFee.setText("(￥0.00)");
                    txtRepayTips.setText("本金0.00元+利息0.00元");
                    calculatorBean.money = null;
                    txtTips.setText(getServiceTips("0", "0.00"));
                    return;
                }
                if (UI.toFloat(editMoney) > auth_money) {
                    editMoney.setText((int) auth_money + "");
                    return;
                }
                if (mHandler.hasMessages(1002)) {//信息搜索
                    mHandler.removeMessages(1002);
                }
                //1000: //EditText输入变化延迟时间1s
                mHandler.sendEmptyMessageDelayed(1002, 700);
            }
        });
    }

    private void initData(){
        borrowMoneyTipsDilaog.setBreakFee(totalData.break_fee);
        txtTitle.setText(totalData.name);
        txtMenuFour.setText("年化利率" + totalData.rate + "%");
        txtBorrowPlace.setText(totalData.lender);

        submitBean.company_id = totalData.company_id;
        submitBean.channel_id = totalData.channel_id;

        calculatorBean.channel_id = totalData.channel_id;
        calculatorBean.company_id = totalData.company_id;
        if (totalData.days != null && totalData.days.size() != 0) {
            String day = totalData.days.get(0);
            calculatorBean.day = day;
            txtMenuOne.setText(day + "天");
            submitBean.day = day;
        }
        auth_money = Float.valueOf(totalData.auth_money);
        Spanned txt_borrow_tips = Spans.with(this).font("最多可借", getResources().getDimensionPixelSize(R.dimen.x24), 0xffBBC7D6).
                font(totalData.auth_money, getResources().getDimensionPixelSize(R.dimen.x24), 0xff0072FF).
                font("元，可提前还，利息按天计算", getResources().getDimensionPixelSize(R.dimen.x24), 0xffBBC7D6).
                build();
        txtBorrowTips.setText(txt_borrow_tips);
    }


    private void getDealIndexDetail(String company_id, String channel_id) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();
        DealIndexDetailBean bean = new DealIndexDetailBean();
        bean.company_id = company_id;
        bean.channel_id = channel_id;
        Api.api_service.getDealIndexDetail(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    totalData = result.data;
                    initData();
                });
    }

    @Override
    public boolean handleMessage(Message message) {
        switch (message.what) {
            case 1002://输入1s后显示(1s内输入数据无变化)
//                ToastUtil.makeText(this, "我变化啦");
                if (UI.toString(editMoney).length() != 0) {
                    calculatorBean.money = UI.toString(editMoney);
                    getDealInfo();
                } else {

                }
                break;
        }
        return false;
    }

    private static class MyHandler extends Handler {
        WeakReference<BorrowStepActivity> mActivityReference;

        MyHandler(BorrowStepActivity activity) {
            mActivityReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            BorrowStepActivity activity = mActivityReference.get();
            if (activity != null) {
                activity.handleMessage(msg);
            }
        }
    }


    //    查看银行卡是否需要签约
    private void getBankPresign(String bankcard_id) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();
        BankcardPresignBean bean = new BankcardPresignBean();
        bean.bankcard_id = bankcard_id;
        Api.api_service.getBankPresign(bean).compose(RxLifeUtil.checkOnMultipleRequest(this, loadingDialog)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    loadingDialog.dismiss();
                    if (result.data.isSign.equals("Y")) {
                        isNeedBankSign = true;
                        phoneIdentityDilaog.setSignUniqueCode(result.data.signUniqueCode, result.data.mobile);
                        phoneIdentityDilaog.show();
                    } else {
                        isNeedBankSign = false;
                        getDealApply();
                    }
                });
    }


    //    计算金额
    private void getDealInfo() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingSec.setVisibility(View.VISIBLE);

        Api.api_service.getDealInfo(calculatorBean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingSec.setVisibility(View.GONE);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    DealInfoModel.DataBean item = result.data;
                    txtGetMoney.setText("￥" + item.money);
                    txtRepayMoney.setText("￥" + item.true_money);
                    txtTime.setText(item.repay_date);
                    txtServiceFee.setText("（￥" + item.manage_fee + "）");
                    txtRepayTips.setText("本金" + item.money + "元+利息" + item.money_fee + "元");


                    txtTips.setText(getServiceTips(item.manage_rate, item.manage_fee));
                    borrowMoneyTipsDilaog.setData(item);
                });
    }

    private Spanned getServiceTips(String one, String two) {
        return Spans.with(this).font("注：1、信用评估费为智信派平台根据您当前资料提供信用评估服务，并将生成信用报告授权给贷款服务提供方过程中所产生的费用；\n2、根据您目前信用情况，信用评估费为交易金额", x22, 0xffBBC7D6).
                font(one + "%(￥" + two + ")", x22, 0xff337CFC).
                font("，将在您借款申请通过后从银行卡划扣，借款申请审核失败不收费用。信用评估费将根据您个人情况变动，请保持良好信用情况；\n3、勾选即代表您同意条款并支付信用评估费。", x22, 0xffBBC7D6).
                build();
    }

    //    申请借款
    private void getDealApply() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();

        Api.api_service.getDealApply(submitBean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    UserInfoGlobal.setDealId(result.data.deal_id);
                    Util.startActivity(this, LoanAgreementActivity.class);
                    finish();
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(BorrowUseEvent msg) {
        submitBean.use_typeid = msg.use_typeid;
        submitBean.use_desc = msg.use_desc;
        submitBean.use_photos = msg.use_photos;
        txtMenuThree.setText(msg.type_name);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unbiner.unbind();
        unbiner = null;
    }

    @OnClick({R.id.btn_check_one, R.id.btn_tips, R.id.btn_all, R.id.btn_menu_one, R.id.btn_menu_two, R.id.btn_menu_three, R.id.btn_menu_four, R.id.layout_bank, R.id.btn_check, R.id.btn_submit})
    public void onViewClicked(View view) {
        if (UI.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.btn_tips:
                Dialog.showDefaultDialog(this, "", "认证越多，智信分也就越高可借款额度就越高", "取消", "认证中心", false, new Dialog.DialogDefaultClickListener() {
                    @Override
                    public void confirm() {
                        EventBus.getDefault().post(new ChangeHomePageEvent(2));
                        finish();
                    }

                    @Override
                    public void cancel() {

                    }
                });
                break;
            case R.id.btn_all:
                editMoney.setText((int) auth_money + "");
                break;
            case R.id.btn_menu_one:
                selectMenuDilaog.setData("time", totalData.days);
                selectMenuDilaog.show();
                break;
            case R.id.btn_menu_two:
                borrowMoneyTipsDilaog.show();
                break;
            case R.id.btn_menu_three:
                Intent intent = new Intent(this, BorrowUseActivity.class);
                intent.putParcelableArrayListExtra("data", totalData.use_type);
                startActivity(intent);
                overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
            case R.id.btn_menu_four:
                break;
            case R.id.layout_bank:
                bankSelectDialog.show();
                break;
            case R.id.btn_check:
                isAgree = !isAgree;
                if (isAgree) {
                    btnCheck.setImageResource(R.mipmap.img_step_check);
                } else {
                    btnCheck.setImageResource(R.mipmap.img_step_uncheck);
                }

                break;

            case R.id.btn_check_one:
                isAgreeOne = !isAgreeOne;
                if (isAgreeOne) {
                    btnCheckOne.setImageResource(R.mipmap.img_step_check);
                } else {
                    btnCheckOne.setImageResource(R.mipmap.img_step_uncheck);
                }
                break;
            case R.id.btn_submit:
//                phoneIdentityDilaog.show();
                submitBean.money = UI.toString(editMoney);

                if (submitBean.checkAll()) {
                    if (!isAgreeOne) {
                        ToastUtil.makeTipsText("请勾选同意协议");
                        return;
                    }
                    if (!isAgree) {
                        ToastUtil.makeTipsText("请同意信用评估费");
                        return;
                    }
                    if (Float.valueOf(submitBean.money) % 100 != 0) {
                        ToastUtil.makeTipsText("请输入100的整数");
                        return;
                    }
                    if (isNeedBankSign) {
                        getBankPresign(submitBean.bankcard_id);
                    } else {
                        getDealApply();
                    }


                }
                break;
        }
    }
}
